let imgElement = null;
let inputCanvas = null;
let outputCanvas = null;

function checkOpenCvDependencies() {
    const requiredFunctions = [
        'imread',
        'imshow',
        'cvtColor',
        'inRange',
        'findContours'
    ];
    
    return requiredFunctions.every(func => 
        typeof cv[func] === 'function'
    );
}

function initializeApp() {
    console.log('Initializing app...');
    try {
        // 等待OpenCV.js完全加载
        if (typeof cv === 'undefined' || !cv.Mat) {
            console.log('等待 OpenCV.js 加载...');
            setTimeout(initializeApp, 500); // 增加延迟时间
            return;
        }

        // 检查OpenCV版本和可用接口
        console.log('OpenCV.js 版本:', cv?.version?.major + '.' + cv?.version?.minor + '.' + cv?.version?.revision);
        
        // 初始化UI组件
        document.getElementById('fileInput').addEventListener('change', function(e) {
            console.log('文件已选择:', e.target.files[0]);
            const file = e.target.files[0];
            if (!file) return;

            // 创建图片对象
            const img = new Image();
            img.onload = function() {
                console.log('图片已加载, 尺寸:', img.width, 'x', img.height);
                try {
                    detectContamination(img);
                } catch (error) {
                    console.error('处理图片时发生错误:', error);
                }
            };

            // 添加错误处理
            img.onerror = function() {
                console.error('图片加载失败');
            };

            // 从文件创建URL
            img.src = URL.createObjectURL(file);
        });
        inputCanvas = document.getElementById('canvasInput');
        outputCanvas = document.getElementById('canvasOutput');

        // 设置canvas属性以优化性能
        inputCanvas.willReadFrequently = true;
        outputCanvas.willReadFrequently = true;
        
        console.log('应用初始化完成');
        
    } catch (error) {
        console.error('初始化错误:', error);
        document.getElementById('status').textContent = '初始化失败: ' + error.message;
        document.getElementById('status').style.color = 'red';
    }
}

function handleImageUpload(e) {
    try {
        if (typeof cv === 'undefined' || !cv.Mat) {
            alert('OpenCV.js 还未加载完成，请稍候...');
            return;
        }

        const file = e.target.files[0];
        if (!file) return;

        imgElement = new Image();
        imgElement.onload = function() {
            try {
                // 设置最大尺寸
                const maxWidth = 500;
                const maxHeight = 400;
                
                // 计算缩放比例
                let scale = 1;
                if (this.width > maxWidth || this.height > maxHeight) {
                    const scaleX = maxWidth / this.width;
                    const scaleY = maxHeight / this.height;
                    scale = Math.min(scaleX, scaleY);
                }
                
                // 计算新尺寸
                const newWidth = Math.floor(this.width * scale);
                const newHeight = Math.floor(this.height * scale);

                // 设置canvas尺寸
                inputCanvas.width = newWidth;
                inputCanvas.height = newHeight;
                outputCanvas.width = newWidth;
                outputCanvas.height = newHeight;

                // 绘制原图
                const ctxInput = inputCanvas.getContext('2d', { willReadFrequently: true });
                ctxInput.drawImage(imgElement, 0, 0, newWidth, newHeight);
                
                detectContamination(this);
            } catch (error) {
                console.error('处理图片时发生错误:', error);
                alert('处理图片时发生错误: ' + error.message);
            }
        }
        imgElement.src = URL.createObjectURL(file);
    } catch (error) {
        console.error('上传处理错误:', error);
        alert('上传处理错误: ' + error.message);
    }
}

function detectContamination(img) {
    // 获取 canvas 元素
    const inputCanvas = document.getElementById('canvasInput');
    const outputCanvas = document.getElementById('canvasOutput');
    
    if (!inputCanvas || !outputCanvas) {
        console.error('Canvas 元素未找到');
        return;
    }

    // 设置 canvas 尺寸
    inputCanvas.width = img.width;
    inputCanvas.height = img.height;
    
    // 获取绘图上下文
    const ctxInput = inputCanvas.getContext('2d', { willReadFrequently: true });
    if (!ctxInput) {
        console.error('无法获取 canvas 上下文');
        return;
    }

    // 绘制图片
    ctxInput.drawImage(img, 0, 0);
    
    let src, dst, mask, contours, hierarchy, low, high, result;
    try {
        // 转换为OpenCV格式
        src = cv.imread(inputCanvas);
        dst = new cv.Mat();
        
        // 转换为HSV色彩空间
        cv.cvtColor(src, dst, cv.COLOR_RGBA2RGB);
        cv.cvtColor(dst, dst, cv.COLOR_RGB2HSV);
        
        // 设定白色的HSV范围
        low = new cv.Mat(dst.rows, dst.cols, dst.type(), [0, 0, 200, 0]);
        high = new cv.Mat(dst.rows, dst.cols, dst.type(), [180, 30, 255, 255]);
        
        // 创建掩码
        mask = new cv.Mat();
        cv.inRange(dst, low, high, mask);
        
        // 反转掩码以获取非白色区域
        cv.bitwise_not(mask, mask);
        
        // 找到轮廓
        contours = new cv.MatVector();
        hierarchy = new cv.Mat();
        cv.findContours(mask, contours, hierarchy, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE);
        
        // 在原图上标记污染区域
        result = cv.imread(inputCanvas);
        for (let i = 0; i < contours.size(); i++) {
            let color = new cv.Scalar(255, 0, 0, 255);
            cv.drawContours(result, contours, i, color, 2);
        }
        
        // 显示结果
        cv.imshow(outputCanvas, result);
        
        // 分析污染类型
        analyzeContamination(contours, mask);
        
    } catch (error) {
        console.error('处理图片时发生错误:', error);
        throw error;
    } finally {
        // 释放内存
        src?.delete();
        dst?.delete();
        mask?.delete();
        contours?.delete();
        hierarchy?.delete();
        low?.delete();
        high?.delete();
        result?.delete();
    }
}

function analyzeContamination(contours, mask) {
    let resultDiv = document.getElementById('result');
    let resultText = '<h3>检测结果：</h3>';
    
    if (contours.size() === 0) {
        resultText += '<p>未检测到污染</p>';
    } else {
        resultText += `<p>检测到 ${contours.size()} 处异常区域：</p><ul>`;
        
        for (let i = 0; i < contours.size(); i++) {
            let contour = contours.get(i);
            let area = cv.contourArea(contour);
            let perimeter = cv.arcLength(contour, true);
            
            // 基于面积和周长的简单形状分析
            if (area < 100) {
                resultText += '<li>小污点或斑点</li>';
            } else if (perimeter / Math.sqrt(area) > 5) {
                resultText += '<li>可能是破洞或裂痕</li>';
            } else {
                resultText += '<li>较大面积的染色或污渍</li>';
            }
        }
        resultText += '</ul>';
    }
    
    resultDiv.innerHTML = resultText;
} 